# -*- coding:utf-8 -*-
"""
币头条
http://www.tokenpapa.com/
"""
import requests
import json
from cs import day
from WriteData import writedata
from Tk import genearteMD5

headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'Content-Length': '25',
    'Content-Type': 'application/json',
    'Host': 'www.tokenpapa.com',
    'X-Requested-With': 'XMLHttpRequest',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}


def post_html_text(url, data):
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates(url, data):
    text = post_html_text(url, json.dumps(data))
    if not text:
        return None
    text = json.loads(text)
    datas = text['data']
    dates = [date['updated'][:10] for date in datas]
    return dates


def count_process_xw():  # 新闻
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while a < 200:
        data = {'count': 10, 'page': a}
        url = 'http://www.tokenpapa.com/weice/tokenpapa/findByArticlesList.do'
        print('----币头条新闻最新获取第{}页----'.format(a))
        a += 1
        dates = get_dates(url, data)
        if not dates:
            continue
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        if d4 > 0:

            break
    return (d1, d2, d3)


def main():
    u = '币头条'
    t1 = count_process_xw()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
